/**
 * 选择树弹窗
 */
import SearchTree from '@/biz-components/search-tree';
import { Modal, Input, message, InputRef } from "antd";
import {formatMessage} from "@/utils/i18n-transform";
import {useRef, useState, useEffect} from "react";
import {xhrPostJson} from "@/services";
import { useField, useForm } from '@formily/react';
import './index.less';

interface SearchTreeModalProps {
    value?: string,
    api?: any,
    disabled?: boolean,
    editable?: boolean,
    allowClear?: boolean;
    [key: string]: any,
}

// todo 查组织机构的接口不能用
export const SearchTreeModal = (props: SearchTreeModalProps) => {
    const { api, onChange, allowClear = false } = props;
    const [visible, setVisible] = useState<boolean>(false);
    const curValue = useRef<string>('');
    const inputRef = useRef<InputRef>(null);
    const [displayValue, setDisplayValue] = useState<string>('');
    const [v, setv] = useState<string>();
    const [o, seto] = useState<any>();
    const field = useField();
    const form = useForm();
    const onOk = () => {
        if (!v) {
            message.warn('请选择部门');
            return;
        }
        setVisible(false);
        setDisplayValue(o.name || '');
        setDeptName(o.name || '');
        onChange(v, o);
    };
    const handleSelectNode = (obj: any) => {
        // if (obj.type === 'DEPARTMENT') {
        //     setv(obj?.code);
        //     seto(obj);
        // } else {
        //     message.warn('只能选择部门');
        // }
        setv(obj?.code);
        seto(obj);
    };
    const click = () => {
        inputRef.current?.blur?.();
        setVisible(true);
    }
    const setDeptName = (name: string) => {
        console.log(field?.path?.entire, 'abcdefg', name)
        form.setValuesIn(`${field?.path?.entire}Name`, name);
    }
    useEffect(() => {
        console.log('search-tree-modal', props?.value, curValue?.current, (!props?.value || props?.value === curValue?.current));
        if (!props?.value || props?.value === curValue?.current) {
            return;
        }
        console.log('curValue', (!props?.value || props?.value === curValue?.current));
        curValue.current = props?.value || '';
        const detailUrl = api?.detailUrl || '/sym/org/detailJson';
        xhrPostJson(detailUrl, { code: props?.value, pageCode: 'ORGMAINT_L' }).then(res => {
            if (!res?.success) {
                return;
            }
            const name = res?.result?.trace || res?.result?.name || '';
            setDisplayValue(name);
            setDeptName(name);
        });
    }, [props?.value]);
    const inputValueChange = (e: any) => {
        setDisplayValue(e.target.value);
        inputRef.current?.blur?.();
        if(!e.target.value) {
            onChange('', {});
        }
    }
    return <>
        <Input
            // readOnly
            allowClear={allowClear}
            value={displayValue}
            ref={inputRef}
            disabled={props?.disabled || !props?.editable}
            className="search-tree-modal-input"
            onChange={inputValueChange}
            onClick={click}/>
        <Modal
        width={800}
        bodyStyle={{
        height: 400
        }
        }
        wrapClassName="search-tree-modal-body"
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={onOk
        }
        title="选择部门">
            <SearchTree
                onSelect={handleSelectNode}
                canSearch
                keyName={'code'}
                titleName={'name'}
                titleWithKey={true}
                defaultSelectedKeys={props?.value ? [props?.value] : []}
                disabledFunc={(it) => {
                    return +it?.virtualFlag === 1;
                }}
                api={{
                    type: 'GET',
                    url: api?.url || '/sym/department/hierarchy',
                    params: { children: true }
                }}
            />
    </Modal></>;
};

export default SearchTreeModal;
